﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KaiXin001er.Objects;
using KaiXin001er.UTIL;
using System.Threading;

namespace KaiXin001er
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }


        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm form = new AboutForm();
            form.ShowDialog();
        }

        Account currentAcct = null;







        /// <summary>
        /// 程序配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void customizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form form = new ProgrameConfiger();
            form.ShowDialog();
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentAcct == null) return;
            
            currentAcct.Enable = cb_isEnable.Checked;
            currentAcct.IsHouseGame = cb_gardener.Checked;
            currentAcct.IsParkGame = cb_parker.Checked;
            currentAcct.StartSeq = numUpandDown.Value;

            currentAcct.IsPark = cb_parkerEnable.Checked;
            currentAcct.IsRace = cb_racerEnable.Checked;

            currentAcct.IsGarden = cb_gardenerEnable.Checked;
            currentAcct.IsAntiGrass = cb_antigrassEnable.Checked;
            currentAcct.IsAntivirmin = cb_antivirminEnable.Checked;
            currentAcct.IsGardenWater = cb_gardenWaterEnable.Checked;
            currentAcct.IsGardenSteal = cb_gardenStealEnable.Checked;

            currentAcct.IsRancher = cb_rancherEnable.Checked;
            currentAcct.IsRancherWater = cb_ranchWaterEnable.Checked;
            currentAcct.IsRancherSteal = cb_ranchStealEnable.Checked;
            currentAcct.IsHelpProd = cb_helpprodEnable.Checked;

            currentAcct.IsDoJob = cb_emplEnable.Checked;

            ConfigManager.SaveAcctConfig();
            refreshDataGridView();
        }
        /// <summary>
        /// 主要是装载帐户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {

            AccountView.AutoGenerateColumns = false;
            refreshDataGridView();
        }
        /// <summary>
        /// 执行单次循环
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //排序
            ConfigManager.AcctList.Sort(new AcctComparer());
            dw = new DebugWindow();
            rungThread = new Thread(new ThreadStart(Runthread));
            rungThread.IsBackground = true;
            rungThread.Start();
            dw.OnStopForce = new DebugWindow.StopForce(OnStopForce);
            dw.startDebuger();
            //dw.Dispose();

        }
        private Thread rungThread;
        DebugWindow dw;
        private void Runthread()
        {

            foreach (Account acct in ConfigManager.AcctList)
            {
                try
                {
                    if (!acct.Enable) continue;

                    KaiXin001er.Logic.Kaixin001Player player = new KaiXin001er.Logic.Kaixin001Player(acct);
                    KaiXin001er.Logic.EventProvider.MsgDelegate msgdelegate = new KaiXin001er.Logic.EventProvider.MsgDelegate(dw.onMessage);
                    player.OnMsg += msgdelegate;
                    if (player.SignOn())
                        player.PlayPlay();
                    player.SignOff();
                    player.OnMsg -= msgdelegate;
                }
                catch (Exception e)
                {
                    if ((e as System.Threading.ThreadInterruptedException) != null) break;
                    if((e as System.ObjectDisposedException )!=null)break;
                    if (ConfigManager.ProgramConfig.OpenDebug)
                    {
                        Trace.Tracer.trace("[session被强制中断] "+e.Message);
                    }
                    Console.WriteLine(e.Message);
                }
            }

            showTips();
            ConfigManager.SaveAcctConfig();
            //dw.endDebuger();
        }
        /// <summary>
        /// What is new
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateRecordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormWhatSnew whatisnew = new FormWhatSnew();
            whatisnew.ShowDialog();
        }
        private System.Threading.Timer timer;
        /// <summary>
        /// 循环开心
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            try
            {
                if (ConfigManager.ProgramConfig.EnableCycle)
                {
                    ConfigManager.AcctList.Sort(new AcctComparer());
                    dw = new DebugWindow();
                    dw.OnStopForce = new DebugWindow.StopForce(OnStopForce);
                    TimeSpan dueTime = ConfigManager.ProgramConfig.HappyTime - DateTime.Now;
                    TimeSpan period = new TimeSpan(ConfigManager.ProgramConfig.HappyCycle, 0, 0);
                    while (dueTime.TotalMilliseconds < 0) dueTime = dueTime.Add(period);
                    timer = new System.Threading.Timer(new TimerCallback(timeThread), null, dueTime, period);
                    dw.writeMsg2window("第一次启动时间" + DateTime.Now.Add(dueTime).ToString());
                    dw.startDebuger();
                }
                else
                {
                    MessageBox.Show("没有启用循环开心配置不能循环执行阿");
                }
            }
            catch (Exception) { }
        }

        private void timeThread(object state)
        {

            foreach (Account acct in ConfigManager.AcctList)
            {
                try
                {
                    if (!acct.Enable) continue;

                    KaiXin001er.Logic.Kaixin001Player player = new KaiXin001er.Logic.Kaixin001Player(acct);
                    KaiXin001er.Logic.EventProvider.MsgDelegate msgdelegate = new KaiXin001er.Logic.EventProvider.MsgDelegate(dw.onMessage);
                    player.OnMsg += msgdelegate;
                    if (player.SignOn())
                        player.PlayPlay();
                    player.SignOff();
                    player.OnMsg -= msgdelegate;
                }
                catch (Exception) { }
                // TimeSpan ts = new TimeSpan(ConfigManager.ProgramConfig.HappyCycle,0,0);
            }

            showTips();
            ConfigManager.SaveAcctConfig();
        }
        private delegate void showTipsDelegate();
        private void showTips()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new showTipsDelegate(this.showTips));
            }
            else
            {
                tipForm tip = new tipForm();
                tip.tipShow();
            }
        }
        private void OnStopNormal()
        {
            popCurrentAcct();
        }
        private void OnStopForce()
        {
            // 强行关闭线程
            if (rungThread != null && rungThread.IsAlive)
            {
                try
                {
                    rungThread.Interrupt();
                }
                catch (Exception) { }
            }
            //强行关闭timer
            if (timer != null)
            {
                try
                {
                    timer.Dispose();
                }
                catch (Exception) { }
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            tipForm tip = new tipForm();
            tip.tipShow();
        }
        private FormWindowState priStat;
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal || this.WindowState == FormWindowState.Maximized)
            {
                priStat = this.WindowState;
                this.WindowState = FormWindowState.Minimized;
                if (dw != null && !dw.IsDisposed) dw.WindowState = FormWindowState.Minimized;
            }
            else
            {
                this.WindowState = priStat;
                if (dw != null && !dw.IsDisposed) dw.WindowState = FormWindowState.Normal;
            }

        }
        private void refreshDataGridView()
        {
            if (ConfigManager.AcctList.Count > 0)
            {
                ConfigManager.AcctList.Sort(new AcctComparer());
                this.AccountView.DataSource = null;
                this.AccountView.DataSource = ConfigManager.AcctList;
            }
            //this.AccountView.DataSource = null;
            //this.AccountView.DataSource = ConfigManager.AcctList;
        }
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormNewAccount f = new FormNewAccount();
            if (f.ShowDialog() == DialogResult.OK)
            {
                Account a = new Account();
                a.AcctName = f.userName;
                a.AcctEmail = f.email;
                a.AcctPassword = f.password;
                ConfigManager.AcctList.Add(a);

                //创建完后直接读取用户好友
                this.currentAcct = a;
                btn_reReadFriend_Click(null, null);
            }
        }

        private void btn_reReadFriend_Click(object sender, EventArgs e)
        {
            if (currentAcct == null) return;
            currentAcct.FriendsLoaded = false;
            dw = new DebugWindow();
            rungThread = new Thread(new ThreadStart(readFriendThread));
            rungThread.IsBackground = true;
            rungThread.Start();
            dw.OnStopNormal = new DebugWindow.StopNormal(OnStopNormal);
            dw.OnStopForce = new DebugWindow.StopForce(OnStopForce);
            dw.startDebuger();
        }
        private void readFriendThread()
        {

            KaiXin001er.Logic.Kaixin001Player player = new KaiXin001er.Logic.Kaixin001Player(currentAcct);
            KaiXin001er.Logic.EventProvider.MsgDelegate msgdelegate = new KaiXin001er.Logic.EventProvider.MsgDelegate(dw.onMessage);
            player.OnMsg += msgdelegate;
            if (player.SignOn())
                player.PlayPlay();
            player.SignOff();
            player.OnMsg -= msgdelegate;
            dw.endDebuger();
        }

        private void AccountView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (AccountView.SelectedRows.Count > 0)
            {
                currentAcct = (Account)AccountView.SelectedRows[0].DataBoundItem;
                popCurrentAcct();
            }
        }

        private void popCurrentAcct()
        {
            if (currentAcct == null)
            {
                lb_name.Text = "";
                lb_email.Text = "";
                cb_isEnable.Checked = false;
                numUpandDown.Value = 0;
                cb_parker.Checked = false;
                cb_gardener.Checked = false;
                return;
            }
            lb_name.Text = currentAcct.AcctName;
            lb_email.Text = currentAcct.AcctEmail;
            cb_isEnable.Checked = currentAcct.Enable;
            numUpandDown.Value = currentAcct.StartSeq;
            cb_parker.Checked = currentAcct.IsParkGame;
            cb_gardener.Checked = currentAcct.IsHouseGame;
            lb_FriendCount.Text = currentAcct.Friends.Count + "个好友";
            if (currentAcct.AcctImageLoaded) this.pictureBox1.Image = currentAcct.AcctImage;
            
            cb_parkerEnable.Checked = currentAcct.IsPark;
            cb_racerEnable.Checked = currentAcct.IsRace;

            cb_gardenerEnable.Checked = currentAcct.IsGarden;
            cb_antigrassEnable.Checked = currentAcct.IsAntiGrass;
            cb_antivirminEnable.Checked = currentAcct.IsAntivirmin;
            cb_gardenWaterEnable.Checked = currentAcct.IsGardenWater;
            cb_gardenStealEnable.Checked = currentAcct.IsGardenSteal;

            cb_rancherEnable.Checked = currentAcct.IsRancher;
            cb_ranchWaterEnable.Checked = currentAcct.IsRancherWater;
            cb_ranchStealEnable.Checked = currentAcct.IsRancherSteal;
            cb_helpprodEnable.Checked = currentAcct.IsHelpProd;

            cb_emplEnable.Checked = currentAcct.IsDoJob;
            cb_gardenerEnable_CheckStateChanged(null, null);
            cb_rancherEnable_CheckStateChanged(null,null);

        }

        private void cb_gardenerEnable_CheckStateChanged(object sender, EventArgs e)
        {
            if (this.cb_gardenerEnable.Checked)
            {
                cb_antigrassEnable.Enabled = true;
                cb_antivirminEnable.Enabled = true;
                cb_gardenStealEnable.Enabled = true;
                cb_gardenWaterEnable.Enabled = true;
            }
            else
            {
                cb_antigrassEnable.Enabled = false;
                cb_antivirminEnable.Enabled = false;
                cb_gardenStealEnable.Enabled = false;
                cb_gardenWaterEnable.Enabled = false;
            }
        }



        private void cb_rancherEnable_CheckStateChanged(object sender, EventArgs e)
        {
            if (cb_rancherEnable.Checked)
            {
                cb_ranchWaterEnable.Enabled = true;
                cb_ranchStealEnable.Enabled = true;
                cb_helpprodEnable.Enabled = true;

            }
            else
            {
                cb_ranchWaterEnable.Enabled = false;
                cb_ranchStealEnable.Enabled = false;
                cb_helpprodEnable.Enabled = false;

            }
        }
    }
}
